<template>
  <div class="page-controller">
    <!-- 查询条件区 -->
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :defaultFormNum="7"
      :excludeValues="['startTimeBegin', 'startTimeEnd', 'endTimeBegin', 'endTimeEnd']"
      :wrapperSpan="wrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="processInstanceId" label="流程实例ID">
          <FIInput v-model="state.query.processInstanceId" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="starter" label="流程发起人姓名">
          <FIInput v-model="state.query.starter" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="processDefName" label="流程定义名称">
          <FIInput v-model="state.query.processDefName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="begTime" label="开始时间从">
          <FIDatePicker v-model="state.query.begTime" type="datetime" value-format="YYYYMMDDHHmmss" />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="endTime" label="至">
          <FIDatePicker v-model="state.query.endTime" type="datetime" value-format="YYYYMMDDHHmmss" />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="instStatus" label="流程状态">
          <FISelect
            v-model="state.query.instStatus"
            valueCustom="value"
            :options="[
              { value: '', label: '全部' },
              { value: 'active', label: '活动' },
              { value: 'suspend', label: '挂起' },
              { value: 'finish', label: '结束' },
              { value: 'manual-finish', label: '终止' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>

      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="sequenceId" label="流程序列号">
          <FIInput v-model="state.query.sequenceId" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <!-- 查询结果列表区 -->
    <FITable
      ref="tableRef"
      class="box-radius2 margin-top20"
      title="记录集"
      :id="`result_${tableId}`"
      :data="state.dataList"
      primaryKey="processInstanceId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      :show-save-model="false"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="handleActionClick"
    >
      <!-- 自定义列 moduleEname1 -->
      <!-- <template #trace="{ scope }">
        <FIButton size="small" link type="primary">流程图</FIButton>
      </template> -->

      <template #headerBtn>
        <FIPopconfirmBtn
          title="您是否确认激活所选流程实例吗？"
          beforePopText="请至少选择一条数据！"
          buttonText="激活"
          :btn-binds="{ id: 'active', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="handleOperate('active')"
        />
        <FIPopconfirmBtn
          class="margin-left12"
          title="您确定要删除所选流程实例吗？"
          beforePopText="请至少选择一条数据！"
          buttonText="删除"
          :btn-binds="{ id: 'delete', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="handleOperate('delete')"
        />
        <FIPopconfirmBtn
          class="margin-left12"
          title="您确定要终止所选流程实例吗？"
          beforePopText="请至少选择一条数据！"
          buttonText="终止"
          :btn-binds="{ id: 'end', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="handleOperate('end')"
        />
        <FIPopconfirmBtn
          class="margin-left12"
          title="您确定要挂起所选流程实例吗？"
          beforePopText="请至少选择一条数据！"
          buttonText="挂起"
          :btn-binds="{ id: 'suspend', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="handleOperate('suspend')"
        />
        <!-- <el-button class="margin-left12" :loading="exportLoading" type="primary" @click="exportClick">导出</el-button> -->
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import FIDatePicker from '@/components/FIDatePicker.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { useMessage } from '@/hooks/message' // 通用message消息提示框
import type { PageConfig, Column } from '@/types/components'
import { useRoute, useRouter } from 'vue-router'

import { initSearchData, openUrlFn } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
// 路由对象
const route = useRoute()
const router = useRouter()
// el-col span栅格占据的列数
const wrapperSpan = 8
// 表格是否显示加载中
const isTableLoading = ref(false)
// 页面编码
const tableId = 'ProcInstInfo'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 表格对象
const tableRef = ref(null)
const state = reactive({
  // 查询条件
  query: {
    processInstanceId: '', // 流程实例ID
    starter: '', // 流程发起人姓名
    processDefName: '', // 流程定义名称
    // taskStartTime: '', // 流程开始时间
    begTime: '', // 流程开始时间起点
    endTime: '', // 流程开始时间终点
    instStatus: '', // 流程实例状态
    sequenceId: '', // 流程序列号
    current: 1,
    size: 10,
  },
  // 表格数据
  dataList: [],
})
// 页面配置
const pageConfig: PageConfig = reactive({
  total: 0, // 总条数
  currentPage: 1, // 当前页码
})
// 表格列数据
const columns: Column[] = reactive([
  // {
  //   label: '流程图',
  //   prop: 'trace',
  //   align: 'center',
  //   width: '100',
  // },
  {
    label: '流水号',
    prop: 'sequenceId',
    align: 'center',
    width: '200',
  },
  {
    label: '流程定义名称',
    prop: 'processDefName',
    align: 'center',
    width: '150',
  },
  {
    label: '发起人',
    prop: 'starter',
    align: 'center',
    width: '150',
  },
  {
    label: '开始时间',
    prop: 'startTime',
    align: 'center',
    width: '160',
    editType: 'date-picker',
  },
  {
    label: '完成时间',
    prop: 'endTime',
    align: 'center',
    width: '160',
    editType: 'date-picker',
  },
  {
    label: '持续时间',
    prop: 'duration',
    align: 'center',
    width: '170',
  },
  {
    label: '状态',
    prop: 'instStatus',
    align: 'center',
    width: '130',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'active', label: '活动' },
        { value: 'suspend', label: '挂起' },
        { value: 'finish', label: '结束' },
        { value: 'manual-finish', label: '终止' },
      ],
    },
  },
  {
    label: '流程实例ID',
    prop: 'processInstanceId',
    align: 'center',
    minWidth: '150',
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [{ id: 'trace', type: '查看流程图' }],
  },
])
// 选中列表集合
const checkedRows = ref([])
// 选中列表集合值改变回调函数
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
// 分页大小改变回调函数
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
// 分页页码改变回调函数
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn()
}
// watch(
//   () => state.query.taskStartTime,
//   (newVal) => {
//     if (newVal.length == 2) {
//       state.query.startTimeBegin = newVal[0]
//       state.query.startTimeEnd = newVal[1]
//     } else {
//       state.query.startTimeBegin = ''
//       state.query.startTimeEnd = ''
//     }
//   }
// )
watch(
  () => state.query.begTime,
  (newVal) => {
    if (newVal && state.query.endTime) {
      if (state.query.endTime < state.query.begTime) {
        useMessage().error('开始时间不能大于结束时间')
      }
    }
  }
)
// 搜索查询函数
const searchFn = (type?: string, columnsVal?: any) => {
  // 页面搜索数据组装
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  state.query.current = pageConfig.currentPage
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // useMessage().error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
// 激活、终止、挂起函数
const handleOperate = (type) => {
  if (!checkedRows.value.length) {
    useMessage().warning('请至少选择一条数据！')
    return
  }
  let ids = []

  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.processInstanceId) ids.push(item?.processInstanceId)
    })

  // let apiUrl = ''
  let apiUrl = proxy.$Button_api(type, route.name)
  let successMsg = '操作成功！'
  if (type === 'delete') {
    // 删除
    // apiUrl = '/bpm-service/ProcInstInfo/deleteInst'
    successMsg = '删除成功！'
  } else if (type === 'active') {
    // 激活
    // apiUrl = '/bpm-service/ProcInstInfo/activeInst'
    successMsg = '激活成功！'
  } else if (type === 'end') {
    // 终止
    // apiUrl = '/bpm-service/ProcInstInfo/endInst'
    successMsg = '终止成功！'
  } else if (type === 'suspend') {
    // 挂起
    // apiUrl = '/bpm-service/ProcInstInfo/suspendInst'
    successMsg = '挂起成功！'
  } else {
    return
  }
  isTableLoading.value = true
  // const obj = {
  //   ActiveProcInstIN: {
  //     processInstanceIds: ids,
  //     description: '激活',
  //   },
  // }
  apiRequestPost(apiUrl, { processInstanceId: ids })
    // apiRequestPost(apiUrl, obj)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(successMsg)
        state.query.current = 1
        searchFn()
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}

// 操作按钮回调
const handleActionClick = (item, rowData, btnInfo) => {
  router.push({
    name: 'EWPITrace',
    query: {
      id: rowData.processInstanceId,
    },
  })
  // let url = `${location.origin}/portal-vue/EW/PI/EWPITrace?id=${rowData.processInstanceId}`
  // window.open(url, '_blank')
  // openUrlFn(item.id, rowData)
}
//导出
const exportLoading = ref(false)
const exportClick = () => {
  exportLoading.value = true
  apiRequestPost('/bpm-service/ProcInstInfo/export', state.query)
    .then(() => {
      exportLoading.value = false
      useMessage().success('导出成功')
    })
    .catch(() => {
      exportLoading.value = false
    })
}

onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  searchFn()
})
</script>
<style lang="less" scoped></style>
